package com.dianzi.certification.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dianzi.certification.entity.UserRole;
import com.dianzi.certification.mapper.UserRoleMapper;
import com.dianzi.certification.service.UserRoleService;
import com.dianzi.certification.vo.R;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author copa
 * @createDate 2022-03-07 22:55
 * @function
 */
@Service
public class UserRoleServiceImpl implements UserRoleService {

    @Resource
    private UserRoleMapper userRoleMapper;

    @Override
    public R<UserRole> findByUserId(Integer userId) {
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper();
        wrapper.eq(null != userId, UserRole::getUserId, userId);

        UserRole userRole = userRoleMapper.selectOne(wrapper);
        if (Objects.isNull(userRole)) {
            return R.error();
        }
        return R.success(userRole);
    }

    @Override
    public UserRole findByUserIdAndRoleId(Integer userId, Integer roleId) {
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper();
        wrapper.eq(null != userId, UserRole::getUserId, userId);
        wrapper.eq(null != roleId, UserRole::getRoleId, roleId);

        UserRole userRole = userRoleMapper.selectOne(wrapper);
        return userRole;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R<String> add(Integer userId, Integer roleId) {
        if (Objects.isNull(findByUserIdAndRoleId(userId, roleId))) {
            int insert = userRoleMapper.insert(
                    new UserRole().setRoleId(roleId).setUserId(userId)
            );
            if (insert < 1) {
                return R.errorMsg("系统异常，请稍后再试~");
            }
        }
        return R.success();
    }
}
